package org.zoomdev.zoom.dao.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.SqlConfig;
import org.zoomdev.zoom.dao.configs.Insert;
import org.zoomdev.zoom.dao.entity.Entity;
import org.zoomdev.zoom.dao.modules.CoreDaoModule;
import org.zoomdev.zoom.dao.utils.LogUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class BatchInsertExecutor implements SqlExecutor {

    private static final Logger log = LoggerFactory.getLogger(CoreDaoModule.NAME);

    public int execute(SqlConfig cfg, Object item) {
        Insert insert = cfg.getInsert();
        Entity entity = cfg.getEntity();
        Connection conn = cfg.openConnection();
        insert.clear();
        insert.prepare(cfg, entity, item, cfg.isIgnoreNull());
        String sql = insert.buildSql(cfg);
        if (CoreDaoModule.logSql) {
            log.info(LogUtils.getSql(sql, insert.getValues()));
        }
        try {
            SqlConfig.BatchConfig stmt = cfg.prepareStatement(conn, sql);
            insert.setParameter(stmt.stmt, 1);
            stmt.addBatch(item);
        } catch (SQLException e) {
            throw new DaoException("执行insert失败", e);
        }
        return 0;
    }

}
